﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GENERIC.EFRepository
{
    public static class Extensions
    {
        /// <summary>
        /// Détermine si un type est un sous-type d'un type générique
        /// </summary>
        /// <param name="toCheck">type à tester</param>
        /// <param name="genericType">type générique</param>
        /// <returns>true si le type est un sous-type d'un type générique, false sinon</returns>
        public static bool IsSubclassOfGeneric(this Type toCheck, Type genericType)
        {
            if (toCheck == typeof(object) || toCheck == null)
            {
                return false;
            }

            var type = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (type == genericType)
            {
                return true;
            }

            if (toCheck.IsInterface)
            {
                foreach (var interfaceType in toCheck.GetInterfaces())
                {
                    if (interfaceType.IsGenericType && IsSubclassOfGeneric(interfaceType, genericType))
                    {
                        return true;
                    }
                }
                return false;
            }
            else
            {
                return IsSubclassOfGeneric(toCheck.BaseType, genericType);
            }
        }
    }
}
